<template>
  <div class="page">
    <v-pageTitle title="部门管理"></v-pageTitle>
    <v-pageHeader>
        <el-button size="small" type="primary" icon="el-icon-circle-plus" v-if="hasPermission('新增')" @click="batchAdd">新增</el-button>
        <!--<el-button size="small" type="danger" icon="el-icon-remove" :disabled="this.sels.length===0" @click="del">删除</el-button>-->
    </v-pageHeader>
    
    <imp-panel>
    
      <el-table size="small" v-loading="table.loading"  
          @row-click="rowClick" 
          :max-height="table.autoHeight"
          :data="table.body" style="width: 100%"
          :header-row-style='headerBg' :header-cell-style="headerBg"
          :default-sort="{prop: 'date', order: 'descending'}">
            <el-table-column
              type="index"
              width="40">
            </el-table-column>
            <el-table-column prop="id" label="部门标识" min-width="100" sortable>
            </el-table-column>
            <el-table-column prop="name" label="部门名称" min-width="150" sortable>
            </el-table-column>
            <el-table-column prop="whoName" label="责任人" min-width="100" sortable>
            </el-table-column>
            <el-table-column prop="parentName" label="父级部门" min-width="150" sortable>
            </el-table-column>
            <el-table-column prop="createByVu" label="创建人" min-width="100" sortable>
            </el-table-column>
            <el-table-column prop="createTime" label="创建日期" min-width="100" sortable>
              <template slot-scope="scope">
                {{getName_date(scope.row.createTime)}}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="150" sortable>
            </el-table-column>
            <el-table-column prop="modifyByVu" label="最后修改人" min-width="120" sortable>
            </el-table-column>
            <el-table-column prop="modifyTime" label="最后修改日期" min-width="150" sortable>
              <template slot-scope="scope">
                {{getName_date(scope.row.modifyTime)}}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="160">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="default"
                  icon="edit"
                  v-if="hasPermission('编辑')"
                  @click="batchEdit(scope.row)">编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  v-if="hasPermission('删除')"
                  @click="handleDel(scope.$index, scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
        </el-table>
    </imp-panel>

    <!--编辑信息界面-->
    <el-dialog title="新增部门" :visible.sync="editFormVisible" @close="dialogClose('dialogForm')" :close-on-click-modal="false">
      <el-form :model="dialogForm" :rules="rules" ref="dialogForm" label-width="80px" size="mini">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="dialogForm.name"></el-input>
        </el-form-item>
        <el-form-item label="责任人" prop="whoId">
          <el-select v-model="dialogForm.whoId" filterable placeholder="请选择">
            <el-option
              v-for="item in whoName_options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="父级部门" prop="parentId">
          <el-select style="width:100%;" v-model="dialogForm.parentId" placeholder="请选择">
            <el-option
              v-for="item in table.body"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="dialogForm.remark"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button  type="primary" @click.native="submitForm('dialogForm')" :loading="editLoading">提交</el-button>
          <el-button @click="resetForm('dialogForm')">重置</el-button>
          <el-button  @click.native="editFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import panel from "@/components/common/panel.vue"
import util from '@/util/util'
  export default {
    components: {
      'imp-panel': panel
    },
    data() {
      // 验证手机号码
      var checkTel = (rule, value, callback) => {
        if(value){
          setTimeout(() => {
            if (!(/^1[34578]\d{9}$/.test(value))) {
              callback(new Error('请填写正确的手机号码格式'));
            } else {
              callback();
            }
          }, 100);
        }else{
          callback();
        }
      };
      // 验证邮箱
      var checkEmail = (rule, value, callback) => {
        if(value){
          setTimeout(() => {
            if (!(/^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g.test(value))) {
              callback(new Error('请填写正确的邮箱格式'));
            } else {
              callback();
            }
          }, 100);
        }else{
          callback();
        }
      };
      // 验证邮编/^[1-9][0-9]{5}$/
      var checkZip = (rule, value, callback) => {
        if(value){
          setTimeout(() => {
            if (!(/^[1-9][0-9]{5}$/.test(value))) {
              callback(new Error('请填写正确的邮编格式'));
            } else {
              callback();
            }
          }, 100);
        }else{
          callback();
        }
      };
      
      return {
        whoName_options:[], //责任人
        table: {
            loading: true,
            body: [],
            autoHeight: 634,
            page: 1,
            pageSize: 10
        },
        // 模糊查询借助字段 存储上次点选的字段
        value_whoName: '',
        value_siteId:'',
        value_whoNameForm: '',
        value_companyName: '',
        value_companyId: '',

        paginationTotal: 0,
        sels:[],

        isAdd: true,
        //编辑基础界面数据
				dialogForm: {
          name:'',  //部门名称
          parentId:'',  //父级部门Id
          remark:'',  //备注
          whoId:'',  //责任人
        },
        // 模糊查询借助字段 存储上次点选的字段
        value_siteIdForm:'',
        value_whoNameForm: '',

        rules: {
          name: [
            { required: true, message: '请输入部门名称', trigger: 'blur' }
          ],
          whoId: [
            { required: true, message: '请输入责任人', trigger: 'blur' }
          ],
          remark: [
            { required: false, message: '请填写备注', trigger: 'blur' }
          ]
        },
        editFormVisible: false,//编辑界面是否显示
        editLoading: false,

        nowDate: util.formatDate.format(new Date(), 'yyyy-MM-dd hh:mm:ss')
      }
    },
    filters: {
      
    },
    methods: {
      //获取责任人
      getWhoNames(){
        let this_ = this;
        let url ='base/baseUser/getBaseUsersByKeywords';  
        //从后台获取到对象数组
        let params = {
            page: 1,
            companyId: "",
            pageSize:10,
            usercode: "",
            name: "",
            enabled: true
          };
      
        util.httpJesen(url,params,function(data){
          
          //在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示  
          for(let i of data.data.records){  
            i.value = i.id;  //将whoName作为value 
            i.label = i.name;  //将siteCode作为lable  
          }
          this_.whoName_options = data.data.records; //责任人
        });
        
      },
      //日期处理
      getName_date(date){
        if(date){
          return util.formatDate.format(new Date(date), 'yyyy-MM-dd')
        }
      },
      headerBg: function(row){
        return { "background": "#EEF1F6","color":"#1F2D3D" };
      },
      
      getTableData(val,flag) {
        // ajax 查询表格数据
        let this_ = this;
        this_.table.loading = true;
        let url = 'base/baseDept/getAllDeps';
        
        let params = {};
        
        util.httpJesen(url,params,function(data){
            this_.table.body = data.data;
            this_.table.loading = false;
            this_.editFormVisible = false;
        });
      },
      
      //显示新增界面
      batchAdd(){
        this.editFormVisible = true;
        this.isAdd = true;
        setTimeout(()=>{
          this.resetForm('dialogForm')
        },200)
      },
      //显示编辑界面
			batchEdit: function (row) {
				this.editFormVisible = true;
        this.isAdd = false;
				this.dialogForm = JSON.parse(JSON.stringify(Object.assign({}, row)));
        this.value_whoNameForm = row.whoName;
        this.value_siteIdForm = row.siteId;
			},
      //close 关闭的回调
      dialogClose(formName){
        this.resetForm(formName);
      },
      rowClick(row) {
        console.log(row.name)
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let this_ = this;
            let obj = Object.assign({}, this_.dialogForm);
            let params = obj;
            console.log(params)

            let url = this_.isAdd ? 'base/baseDept/addDep' : 'base/baseDept/updateDep';
            
            util.httpJesen(url,params,function(data){
                this_.getTableData()
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 重置
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.dialogForm = {
         name:'',
         parentId:'',
         remark: ''
        };
        this.value_siteIdForm = '';
        this.value_whoNameForm = '';
      },
      //删除
			handleDel: function (index, row) {
        let this_ = this;
				this_.$confirm('确认删除该部门吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this_.table.loading = true;
          let url = 'base/baseDept/delDep';
          let params = row.id;
          util.httpJesen(url,params,function(data){
            this_.getTableData();
            this_.table.loading = false;
            this_.$message({
              message: '删除成功',
              type: 'success'
						});
          });
				}).catch(() => {
          
				});
			}
    },
    mounted() {
        //获取table数据
        this.getTableData();
        //获取责任人
        this.getWhoNames();
        //this.baseInfo();

        // 监控浏览器高度 设置table最大高度
        let this_ = this;
        let clientHeight = document.body.clientHeight; 
        this_.table.autoHeight = clientHeight-297;
        window.addEventListener('resize', function(){
          let clientHeight = document.body.clientHeight; 
          this_.table.autoHeight = clientHeight-297;
        })

        this.timer = setInterval(function(){
            this_.nowDate = util.formatDate.format(new Date(), 'yyyy-MM-dd hh:mm:ss');
        },1000);
    },
    beforeDestory(){
        if(this.timer){
            clearInterval(this.timer)
        }
    }
  }
</script>
<style lang="scss" scoped>
.my-autocomplete {
  li {
    line-height: 12px;
    padding: 2px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
      height:24px;
    }
    .label {
      font-size: 12px;
      color: #1381B8;
    }

    .highlighted .label {
      color: #ddd;
    }
  }
}
</style>

    